package com.gnerv.sylvanas.extend.rabbit.autoconfigure;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;

public class MyBeanRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(
            AnnotationMetadata importingClassMetadata, 
            BeanDefinitionRegistry registry) {
        
        // 1. 获取注解上的属性值
        Map<String, Object> attributes = importingClassMetadata
            .getAnnotationAttributes(EnableDynamicBeans.class.getName());
        
        String[] beanClasses = (String[]) attributes.get("value");
        
        // 2. 动态注册每个Bean
        for (String className : beanClasses) {
            try {
                Class<?> clazz = Class.forName(className);
                
                GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
                beanDefinition.setBeanClass(clazz);
                beanDefinition.setScope("singleton"); // 设置作用域
                
                // 使用类名作为Bean名称（首字母小写）
                String beanName = clazz.getSimpleName();
                beanName = beanName.substring(0, 1).toLowerCase() + beanName.substring(1);
                
                registry.registerBeanDefinition(beanName, beanDefinition);
                
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Failed to load class: " + className, e);
            }
        }
    }
}